package com.wk.job.heartbeat.master;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;

import com.wk.database.DB_Mysql;
import com.wk.database.MachineState;
import com.wk.database.UpdatedSlaveMachine;
import com.wk.database.entity.Update;
import com.wk.net.heartbeat.handler.AbsenceListener;

public class AbsentSlaveListener implements AbsenceListener {
	public AbsentSlaveListener() {
		Connection connection = DB_Mysql.getConnection();
		if (connection == null) {
			System.out.println("[AbsentSlaveListener]连接数据库失败");
			this.update = null;
			return;
		}

		Update<UpdatedSlaveMachine> update = new Update<>(UpdatedSlaveMachine.class);
		try {
			update.connect( DB_Mysql.getConnection());
		} catch (SQLException e) {
			this.update = null;
			e.printStackTrace();
		}
		
		this.update = update;
	}

	@Override
	public void onAbsent(Collection<String> recentlyAbsent) {
		for (String slave : recentlyAbsent) {
			System.out.println("[掉线]" + slave);

			try {
				int countUpdated = update.execute(new UpdatedSlaveMachine(slave, MachineState.OFFLINE));
				System.out.println("更新机器状态为掉线。更新数：" + countUpdated);
			} catch (Exception e) {
				e.printStackTrace();
				break;
			}
		}
	}

	private Update<UpdatedSlaveMachine> update;
}
